<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    >
    </el-switch>

    <el-button v-if="draggable" type="success" @click="batchSave"
      >批量保存</el-button
    >
    <el-button type="danger" @click="batchDel">批量删除</el-button>

    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="expandedKey"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="tree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!-- 只有当前层级不是最后一个层级才显示追加按钮 -->
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            添加
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            修改
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            删除
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="category" :model="category" :rules="rules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="category.name"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="category.icon"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" prop="productUnit">
          <el-input v-model="category.productUnit"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="sumbitData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      menus: [], // 三级分类数据
      defaultProps: {
        children: "children", // 子节点对象
        label: "name", // 数据名称
      },
      expandedKey: [], // 默认选中的数组
      dialogVisible: false,
      category: {
        name: "", // 分类名称
        parentCid: 0, // 父分类id
        catLevel: 0, // 层级
        showStatus: 1, // 是否显示[0-不显示，1显示]
        sort: 0, // 排序
        catId: "", // 菜单id
        icon: "", // 图标
        productUnit: "", // 计量单位
      },
      dialogType: "", // 弹窗类型 edit add
      title: "", // 弹出窗标题
      maxLevel: 0, // 最大层级
      updateNodes: [], // 所有修改的节点
      draggable: false, // 是否开启拖拽
      pCid: [],
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        icon: [{ required: true, message: "请输入图标", trigger: "blur" }],
        productUnit: [
          { required: true, message: "请输入计量单位", trigger: "blur" },
        ],
      },
    };
  },
  created() {},
  mounted() {
    this.getMenus();
  },
  methods: {
    /**
     * 函数描述：批量删除
     * @param: caIds id数组
     */
    batchDel() {
      let caIds = [];
      let checkNodes = this.$refs.tree.getCheckedNodes();
      for (let i = 0; i < checkNodes.length; i++) {
        caIds.push(checkNodes[i].catId);
      }
      this.$confirm(`是否批量删除【${caIds}】 菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(caIds, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                type: "success",
                message: "批量删除成功!",
              });
              this.getMenus();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 函数描述: 避免每一次拖拽都调用数据库,只有点击按钮的时候才保存
     */
    batchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "菜单修改成功成功!",
        });
        this.getMenus();
        this.expandedKey = this.pCid;
        this.maxLevel = 0;
        this.updateNodes = [];
      });
    },
    /**
     * 函数描述: 拖拽成功完成时触发的事件
     *          共四个参数，依次为：
     *          被拖拽节点对应的 Node、结束拖拽时最后进入的节点、
     *          被拖拽节点的放置位置（before、after、inner）、event
     */
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // 当前节点拖拽到位置的父节点id、排序、层级
      let pCid = 0;
      let siblings = null;
      if (dropType == "before" || dropType == "after") {
        pCid =
          dropNode.parent.data.catId == undefined
            ? 0
            : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);
      for (let i = 0; i < siblings.length; i++) {
        // 如果当前节点是我拖拽的节点 将新的父id传过去
        if (siblings[i].data.catId == draggingNode.data.catId) {
          let catLevel = draggingNode.data.level;
          if (siblings[i].level != draggingNode.level) {
            catLevel = siblings[i].level;
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            sort: i,
            parentCid: pCid,
            catLevel: catLevel,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }
    },
    /**
     * 函数描述： 修改子节点的层级
     */
    updateChildNodeLevel(node) {
      if (node.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          let cNode = node.childNodes[i].data;
          this.updateNodes.push({
            catId: cNode.catId,
            catLevel: node.childNodes[i].level,
          });
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    /**
     * 函数描述: 拖拽时判定目标节点能否被放置
     *          type 参数有三种情况：'prev'、'inner' 和 'next'，
     *          分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
     * 思路： 被拖动的当前节点以及所在的父节点总层数不能大于3
     */
    allowDrop(draggingNode, dropNode, type) {
      this.countNodeLevel(draggingNode);
      // 当前拖拽节点的最大层级 - 当前节点层级 + 1
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      if (type == "inner") {
        // dropNode.level 插入节点的层级
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }
    },
    /**
     * 函数描述: 找到所有子节点,求出最大深度
     * @param: data 当前拖拽节点的数据
     */
    countNodeLevel(data) {
      if (data.childNodes != null && data.childNodes.length > 0) {
        for (let i = 0; i < data.childNodes.length; i++) {
          if (data.childNodes[i].level > this.maxLevel) {
            this.maxLevel = data.childNodes[i].level;
          }
          this.countNodeLevel(data.childNodes[i]);
        }
      }
    },
    /**
     * 函数描述：获取三级分类所有菜单
     */
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
      });
    },
    /**
     * 函数描述： 新增三级分类
     * data: 当前行数据及子数据
     * parentCid: 父分类id
     * catLevel: 层级
     */
    append(data) {
      this.doRestForm();
      this.dialogType = "add";
      this.title = "添加分类";
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
    },
    /**
     * 函数描述： 添加三级分类
     * @param category 添加的分类数据
     */
    addCategory() {
      this.$refs["category"].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl("/product/category/save"),
            method: "post",
            data: this.$http.adornData(this.category, false),
          }).then(({ data }) => {
            this.dialogVisible = false;
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.getMenus();
            // 添加后展开菜单
            this.expandedKey = [this.category.catId];
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 函数描述： 修改三级分类并赋值(发送请求获取当前节点最新数据,避免多人操作数据不是最新)
     * @param catId 菜单id
     */
    edit(data) {
      this.dialogType = "edit";
      this.title = "修改分类";
      this.dialogVisible = true;
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },
    /**
     * 函数描述： 修改三级分类向后台请求
     * @param category 修改数据
     */
    editCategory() {
      this.$refs["category"].validate((valid) => {
        if (valid) {
          // 利用对象结构
          let { name, catId, icon, productUnit } = this.category;
          this.$http({
            url: this.$http.adornUrl("/product/category/update"),
            method: "post",
            data: this.$http.adornData(
              { name, catId, icon, productUnit },
              false
            ),
          }).then(({ data }) => {
            this.dialogVisible = false;
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.getMenus();
            // 修改后需要打开节点
            this.expandedKey = [this.category.parentCid];
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 函数描述: 判断添加还是修改调用不同的方法
     */
    sumbitData() {
      if (this.dialogType == "add") {
        this.addCategory();
      } else {
        this.editCategory();
      }
    },
    /**
     * 函数描述： 删除三级分类
     * data: 当前行数据及子数据
     * node： el-tree 属性
     */
    remove(node, data) {
      console.log("删除三级分类node", node);
      let ids = [data.catId];
      this.$confirm(`是否删除【${data.name}】 菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getMenus();
              // 删除后需要打开删除父节点
              this.expandedKey = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**
     * 重置form表单
     */
    doRestForm() {
      this.category.catId = "";
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.category.showStatus = 1;
      this.category.sort = 0;
    },
    /**
     * 函数描述：取消按钮点击
     */
    cancel() {
      this.dialogVisible = false;
      this.$refs['category'].clearValidate();
    }
  },
};
</script>
<style lang='scss'  scoped>
</style>